package cn.smbms.interceptor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.smbms.pojo.Permission;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.utils.Constants;

public class SysInterceptor extends HandlerInterceptorAdapter {

	@Resource(name = "roleService")
	private static RoleService roleService;

	@SuppressWarnings("unused")
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 1、正式环境，从 session 当中取出数据
		// User user =
		// (User)request.getSession().getAttribute(Constants.USER_SESSION);
		// 2、开发环境，人为把用户对象放到session里面
		User user = new User();
		user.setUserName("张学猛");
		user.setUserPassword("test");
		user.setGender(1);
		user.setUserRole(1);
		request.getSession().setAttribute(Constants.USER_SESSION, user);
		// 拦截的作用-1：session对象校验
		// System.out.println("user=" + user);
		if (user == null) {
			response.sendRedirect(request.getContextPath() + "/login");
			return false;
		} else {
			// 拦截的作用-2：显示公共数据
			if (roleService == null) {// 注解驱动编程
				roleService = (RoleService) WebApplicationContextUtils
						.getRequiredWebApplicationContext(
								request.getServletContext()).getBean(
								"roleService");
			}
			// System.out.println("roleService="+roleService);
			List<Permission> permissions = roleService
					.getPermissionByRoleId(user.getUserRole());
			request.setAttribute("permission", permissions);
			return true;
		}
	}

}
